<?php

namespace App\Http\Services;

use App\Http\Model\FinanceUnion;
use App\Http\Model\Hint;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use Illuminate\Support\Facades\DB;

class FinanceUnionServices extends CommonServices
{
    protected $financeUnion;
    protected $modelUser;
    protected $modelUnion;
    protected $modelUnionUser;

    public function __construct()
    {
        parent::__construct();

        $this->financeUnion = new FinanceUnion();
        $this->modelUser = new User();
        $this->modelUnion = new Union();
        $this->modelUnionUser = new UnionUser();
    }


    /**
     * 检索指定高管用户信息
     * @param int $uuid 用户uuid
     * @param int $unionId 公会Id
     * @return string|int
     */
    public function getUserInfoByUserUid($uuid, $unionId)
    {
        $userData = $this->modelUser->get_current_user();
        // 校验是否登录
        if (empty($userData)) {
            return Hint::LOGIN_OUT;
        }


        // 获取用户信息
        $userInfo = $this->modelUser->get_user_by_uid($uuid);
        if (empty($userInfo)) {
            return Hint::USER_NOT_EXIST;
        }

        // 判断用户是否在当前公会下
        $findResult = $this->modelUnionUser->getUserIdsByUnionId($unionId);

        if (empty($findResult)) {
            return Hint::FINANCE_UNION_USER_NOT_BIND;
        }
        $baseUserArr = array_column($findResult,'user_id');

        if (!in_array($userInfo['user_id'], $baseUserArr)) {
            return Hint::FINANCE_UNION_USER_NOT_EXIST;
        }

        // 验证用户是否被封号
        $isForbid = $this->modelUser->getBlockInfo($userInfo['user_id']);
        if ($isForbid) {
            return Hint::USER_FORBID;
        }

        return $userInfo;
    }


    /**
     * 设置结算用户
     * @param string $unionId 公会Id
     * @param string $settleUserId 结算用户Id
     * @return int
     */
    public function setSettleUser($unionId, $settleUserId)
    {
        $unionId = intval($unionId);
        $settleUserId = intval($settleUserId);

        $userData = $this->modelUser->get_current_user();
        // 校验是否登录
        if (empty($userData)) {
            return Hint::LOGIN_OUT;
        }
        $userId = $userData['user_id'];

        // 校验当前用户是否是公会所有者
        $unionData = $this->modelUnion->getUnionInfo($unionId);
        if (empty($unionData) || $userId != $unionData['un_user_id']) {
            return Hint::AUTH_ERROR;
        }

        // 校验是否可绑定结算用户
        $checkStatus = $this->financeUnion->getFinanceUnionSettingStatus($unionId);
        if ($checkStatus) {
            return Hint::NOT_ALLOWED;
        }
        DB::beginTransaction();
        $this->financeUnion->setSettleUserId($unionId, $userId, $settleUserId);
        // 记录操作日志
        $this->financeUnion->createUnionSetLog($unionId, $settleUserId);
        DB::commit();
        return Hint::SUCCESS;
    }


    /**
     * 设置提现用户
     * @param string $unionId 公会Id
     * @param string $withdrawUserId 提现用户Id
     * @return int
     */
    public function setWithdrawUser($unionId, $withdrawUserId)
    {
        $unionId = intval($unionId);
        $withdrawUserId = intval($withdrawUserId);

        $userData = $this->modelUser->get_current_user();
        // 校验是否登录
        if (empty($userData)) {
            return Hint::LOGIN_OUT;
        }
        $userId = $userData['user_id'];

        // 校验当前用户是否是公会所有者
        $unionData = $this->modelUnion->getUnionInfo($unionId);
        if (empty($unionData) || $userId != $unionData['un_user_id']) {
            return Hint::AUTH_ERROR;
        }

        // 校验是否可绑定提现用户
        $checkStatus = $this->financeUnion->getFinanceUnionSettingStatus($unionId, 1);
        if ($checkStatus) {
            return Hint::NOT_ALLOWED;
        }

        DB::beginTransaction();
        $this->financeUnion->setWithdrawUserId($unionId, $userId, $withdrawUserId);
        // 记录操作日志
        $this->financeUnion->createUnionSetLog($unionId, 0, $withdrawUserId);
        DB::commit();
        return Hint::SUCCESS;
    }


    /**
     * 解绑结算用户/提现用户
     * @param string $unionId 公会Id
     * @param int $type 操作类型 [0：解绑结算用户   1：解绑提现用户]
     * @return int
     */
    public function unbindUser($unionId, $type)
    {
        $unionId = intval($unionId);

        $userData = $this->modelUser->get_current_user();
        // 校验是否登录
        if (empty($userData)) {
            return Hint::LOGIN_OUT;
        }
        $userId = $userData['user_id'];

        // 校验当前用户是否是公会所有者
        $unionData = $this->modelUnion->getUnionInfo($unionId);
        if (empty($unionData) || $userId != $unionData['un_user_id']) {
            return Hint::AUTH_ERROR;
        }

        // 获取指定结算用户/提现用户Id
        if ($type) {
            $appointUserId = $this->financeUnion->getWithdrawUserId($unionId);
        } else {
            $appointUserId = $this->financeUnion->getSettleUserId($unionId);
        }

        DB::beginTransaction();
        // 执行解绑操作
        $this->financeUnion->unbindUser($unionId, $type);
        // 记录操作日志
        if ($type) {
            $this->financeUnion->createUnionSetLog($unionId, 0, $appointUserId, 1);
        } else {
            $this->financeUnion->createUnionSetLog($unionId, $appointUserId, 0, 1);
        }
        DB::commit();
        return Hint::SUCCESS;
    }


    /**
     * 获取公会指定结算用户/提现用户基本信息
     * @param string $unionId 公会Id
     * @param int $type 操作类型 [0：获取结算用户信息   1：获取提现用户信息]
     * @return array
     */
    public function getAppointUserInfo($unionId, $type)
    {
        $unionId = intval($unionId);

        $result = $this->financeUnion->getAppointUserInfo($unionId, $type);
        if (empty($result)) {
            $result['uuid'] = '';
            $result['nickname'] = '';
        } else {
            $userId = $type ? $result['withdraw_user_id'] : $result['settle_user_id'];
            $userArrData = $this->modelUser->get_user_by_uid($userId, false);
            $result['uuid'] = $userArrData['user_uid'];
            $result['nickname'] = $userArrData['nickname'];
        }

        $endTime = $this->financeUnion->getFinanceUnionSettingStatus($unionId, $type);
        if (empty($endTime)) {
            // 为空时证明可以进行绑定用户操作
            $surplusTime = 0;
        } else {
            $surplusTime = $endTime - time();
        }
        $result['surplus_time'] = $surplusTime;
        return $result;
    }


    /**
     * 获取公会绑定记录
     * @param string $unionId 公会Id
     * @return array|int
     */
    public function getBindRecords($unionId)
    {
        $unionId = intval($unionId);

        $userData = $this->modelUser->get_current_user();
        // 校验是否登录
        if (empty($userData)) {
            return Hint::LOGIN_OUT;
        }
        $userId = $userData['user_id'];

        // 校验当前用户是否是公会所有者
        $unionData = $this->modelUnion->getUnionInfo($unionId);
        if (empty($unionData) || $userId != $unionData['un_user_id']) {
            return Hint::AUTH_ERROR;
        }

        // 获取绑定记录
        $bindResult = $this->financeUnion->getFinanceSettingLog($unionId);
        if (empty($bindResult)) {
            return $bindResult;
        }

        // 获取用户信息
        $settleUserIds = array_unique(array_column($bindResult, 'settle_user_id'));
        $withdrawUserIds = array_unique(array_column($bindResult, 'withdraw_user_id'));
        $userIds = array_unique(array_merge($settleUserIds, $withdrawUserIds));
        unset($userIds[array_search(0, $userIds)]);
        $userArrData = $this->modelUser->get_users_by_ids($userIds);
        $userArrData = array_column($userArrData, null, 'user_id');

        foreach ($bindResult as $key => $val) {
            if (!empty($val['settle_user_id'])) {
                if (isset($userArrData[$val['settle_user_id']])) {
                    $bindResult[$key]['nickname'] = $userArrData[$val['settle_user_id']]['nickname'];
                } else {
                    $bindResult[$key]['nickname'] = '';
                }
            }
            if (!empty($val['withdraw_user_id'])) {
                if (isset($userArrData[$val['withdraw_user_id']])) {
                    $bindResult[$key]['nickname'] = $userArrData[$val['withdraw_user_id']]['nickname'];
                } else {
                    $bindResult[$key]['nickname'] = '';
                }
            }
            $bindResult[$key]['date_str'] = date('Y-m-d', strtotime($val['created_at']));
        }
        return $bindResult;
    }
}